package com.daisuxia.back.controller;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.service.IRiskUserService;
import com.daisuxia.back.service.ITaskJob;
import com.daisuxia.back.utils.DwzResult;
import com.daisuxia.back.utils.ExcelUtil;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SpringUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.pojo.RiskRuleCal;
import com.daisuxia.web.controller.BaseController;
import com.daisuxia.web.pojo.BackUser;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.pojo.UserInfoImage;
import com.daisuxia.web.pojo.UserLimitRecord;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IJsStepRecordService;
import com.daisuxia.web.service.IRepaymentService;
import com.daisuxia.web.service.IUserInfoImageService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.test.HttpRequestCMBHL;
import com.daisuxia.web.util.ConfigConstant;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.GenerateNo;
import com.daisuxia.web.util.HttpUtil;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.SendSmsUtil;

import redis.clients.jedis.JedisCluster;

@Controller
@RequestMapping("backBorrowOrder/")
public class BorrowOrderController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(BorrowOrderController.class);

	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	private IRepaymentService repaymentService;
	@Autowired
	public IUserService userService;
	@Autowired
	private IUserInfoImageService userInfoImageService;
	@Autowired
	private ITaskJob taskJob;
	@Autowired
	@Qualifier("riskUserService")
	private IRiskUserService riskUserService;

	@Autowired
	JedisCluster jedisCluster;
	
	@Autowired
	private IJsStepRecordService jsStepRecordService;

	@RequestMapping("addUserLimit")
	public void addUserLimit(HttpServletRequest request, HttpServletResponse response, Model model) {

		User user = userService.searchByUserid(Integer.parseInt(request.getParameter("userId")));
		borrowOrderService.addUserLimit(user);
	}

	@RequestMapping("getBorrowPage")
	public String getUserPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		String url = "borrow/borrowList";
		try {

			//12121
			HashMap<String, Object> params = getParametersO(request);
			params.put("noAdmin", Constant.ADMINISTRATOR_ID);
			if (params.containsKey("bType")) {
				if (params.get("bType").equals("fangk")) {// 放款界面看到的状态

					params.put("statusList", Arrays.asList(BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_FKZ, BorrowOrder.STATUS_FKBH, BorrowOrder.STATUS_FKSB));
					url = "borrow/borrowList_fk";
				} else if (params.get("bType").toString().contains("fengk")) {// 风控界面看到的状态

					if (params.get("bType").equals("fengk_Trial")) {// 初审
						params.put("statusList", Arrays.asList(BorrowOrder.STATUS_CSTG, BorrowOrder.STATUS_DCS, BorrowOrder.STATUS_CSBH
						// ,
						// BorrowOrder.STATUS_JSJJ
								));
					} else if (params.get("bType").equals("fengk_Review")) {// 复审

						params.put("statusList", Arrays.asList(BorrowOrder.STATUS_CSTG, BorrowOrder.STATUS_FSBH, BorrowOrder.STATUS_FSTG));
					} else {

						params.put("statusList", Arrays.asList(BorrowOrder.STATUS_CSTG, BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_FSBH,
						// BorrowOrder.STATUS_JSJJ,
								BorrowOrder.STATUS_DCS));
					}

					// url = "borrow/fk_borrowList";
				}

				model.addAttribute("bType", params.get("bType"));
			}

			PageConfig<BorrowOrder> pageConfig = borrowOrderService.findPage(params);
			model.addAttribute("pm", pageConfig);
			// model.addAttribute("borrowStatusMap",
			// BorrowOrder.borrowStatusMap);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return url;
	}
	
	@RequestMapping("getBorrowPageByStatus/{borrowStatus}")
	public String getBorrowPageByParams(HttpServletRequest request, HttpServletResponse response,@PathVariable("borrowStatus") String borrowStatus,  Model model) {
		
//		System.out.println(borrowStatus);
		String url = "borrow/borrowList";
		try {

			HashMap<String, Object> params = getParametersO(request);
			if(StringUtils.isNoneBlank(params.get("sVerifyLoanTime")==null?"":params.get("sVerifyLoanTime").toString())){
				params.put("sVerifyLoanTime", DateUtil.getDate(params.get("sVerifyLoanTime").toString(), "yy-MM-dd hh:mm:ss"));
			}
			if(StringUtils.isNoneBlank(params.get("eVerifyLoanTime")==null?"":params.get("eVerifyLoanTime").toString())){
				params.put("eVerifyLoanTime", DateUtil.getDate(params.get("eVerifyLoanTime").toString(), "yy-MM-dd hh:mm:ss"));
			}
			params.put("noAdmin", Constant.ADMINISTRATOR_ID);
			if (params.containsKey("bType")) {
				if (params.get("bType").equals("fangk")) {// 放款界面看到的状态

//					params.put("statusList", Arrays.asList(BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_FKZ, BorrowOrder.STATUS_FKBH, BorrowOrder.STATUS_FKSB));
					url = "borrow/borrowList_fk";
				} else if (params.get("bType").toString().contains("fengk")) {// 风控界面看到的状态

					if (params.get("bType").equals("fengk_Trial")) {// 初审
//						params.put("statusList", Arrays.asList(BorrowOrder.STATUS_CSTG, BorrowOrder.STATUS_DCS, BorrowOrder.STATUS_CSBH
//					 
//								));
					} else if (params.get("bType").equals("fengk_Review")) {// 复审

//						params.put("statusList", Arrays.asList(BorrowOrder.STATUS_CSTG, BorrowOrder.STATUS_FSBH, BorrowOrder.STATUS_FSTG));
					} else {

//						params.put("statusList", Arrays.asList(BorrowOrder.STATUS_CSTG, BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_FSBH,
//						// BorrowOrder.STATUS_JSJJ,
//								BorrowOrder.STATUS_DCS));
					}

					// url = "borrow/fk_borrowList";
				}else if(params.get("bType").equals("duizhang")) {// 放款界面看到的状态

//					params.put("statusList", Arrays.asList(BorrowOrder.STATUS_FSTG, BorrowOrder.STATUS_HKZ, BorrowOrder.STATUS_FKZ, BorrowOrder.STATUS_FKBH, BorrowOrder.STATUS_FKSB));
					url = "borrow/borrowList_dz";
				} 
				model.addAttribute("bType", params.get("bType"));
			}
			params.put("borrowStatusArray", borrowStatus);//格式1,1,3.5
			PageConfig<BorrowOrder> pageConfig = borrowOrderService.findPage(params);
			model.addAttribute("pm", pageConfig);
			// model.addAttribute("borrowStatusMap",
			// BorrowOrder.borrowStatusMap);
			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getUserPage error", e);
		}
		return url;
	}

	@RequestMapping("getBorrowDetailById")
	public String getBorrowDetailById(HttpServletRequest request, HttpServletResponse response, Model model) {

		HashMap<String, Object> params = this.getParametersO(request);
		Integer id = Integer.valueOf(String.valueOf(params.get("id")));
		BorrowOrder borrow = borrowOrderService.findOneBorrow(id);
		model.addAttribute("borrow", borrow);

		HashMap<String, Object> paramsM = new HashMap<String, Object>();

		paramsM.put("userId", borrow.getUserId());

		List<BorrowOrder> userBorrows = borrowOrderService.findAll(paramsM);
		model.addAttribute("userBorrows", userBorrows);
		User user = userService.searchByUserid(borrow.getUserId());
		String cardNo = user.getIdNumber();
		if (cardNo != null && cardNo.length() >= 18) {
			String yy = cardNo.substring(6, 10); // 出生的年份
			String mm = cardNo.substring(10, 12); // 出生的月份
			String dd = cardNo.substring(12, 14); // 出生的日期
			String birthday = yy.concat("-").concat(mm).concat("-").concat(dd);
			model.addAttribute("birthday", birthday);
			model.addAttribute("age", SpringUtils.calculateAge(birthday, "yy-MM-dd"));
		}
		user.setEducation(User.EDUCATION_TYPE.get(user.getEducation()));
		user.setPresentPeriod(User.RESIDENCE_DATE.get(user.getPresentPeriod()));
		user.setMaritalStatus(User.MARRIAGE_STATUS.get(user.getMaritalStatus()));
		user.setFristContactRelation(User.CONTACTS_FAMILY.get(user.getFristContactRelation()));
		user.setSecondContactRelation(User.CONTACTS_OTHER.get(user.getSecondContactRelation()));
		model.addAttribute("user", user);

		UserCardInfo info = userService.findUserBankCard(borrow.getUserId());
		model.addAttribute("bankCard", info);
		List<UserInfoImage> userInfoImage = this.userInfoImageService.selectImageByUserId(borrow.getUserId());
		model.addAttribute("InfoImage", userInfoImage);
		model.addAttribute("params", params);

		// 查询征信信息
		RiskCreditUser riskCreditUser = riskUserService.findRiskCreditUserByAssetsId(String.valueOf(id));
		if (null != riskCreditUser) {
			model.addAttribute("riskCreditUser", riskCreditUser);
		}

		// 规则查询
		List<RiskRuleCal> riskRuleCalList = riskUserService.findRiskRuleCalByAssetsId(String.valueOf(id));
		model.addAttribute("riskRuleCalList", riskRuleCalList);

		return "borrow/borrowdetail";
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @param borrowOrder
	 * @return
	 */
	@RequestMapping("saveUpdateBorrow")
	public String saveUpdateBorrow(HttpServletRequest request, HttpServletResponse response, Model model, BorrowOrder borrowOrder) {

		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {

			if ("toJsp".equals(String.valueOf(params.get("type")))) {

				Integer id = Integer.valueOf(String.valueOf(params.get("id")));

				// model.addAttribute("borrow",
				// borrowOrderService.findOneBorrow(id));

				BorrowOrder borrow = borrowOrderService.findOneBorrow(id);
				model.addAttribute("borrow", borrow);

				HashMap<String, Object> paramsM = new HashMap<String, Object>();

				paramsM.put("userId", borrow.getUserId());

				List<BorrowOrder> userBorrows = borrowOrderService.findAll(paramsM);
				model.addAttribute("userBorrows", userBorrows);
				User user = userService.searchByUserid(borrow.getUserId());
				String cardNo = user.getIdNumber();
				if (cardNo != null && cardNo.length() >= 18) {
					String yy = cardNo.substring(6, 10); // 出生的年份
					String mm = cardNo.substring(10, 12); // 出生的月份
					String dd = cardNo.substring(12, 14); // 出生的日期
					String birthday = yy.concat("-").concat(mm).concat("-").concat(dd);
					model.addAttribute("birthday", birthday);
					model.addAttribute("age", SpringUtils.calculateAge(birthday, "yy-MM-dd"));
				}
				user.setEducation(User.EDUCATION_TYPE.get(user.getEducation()));
				user.setPresentPeriod(User.RESIDENCE_DATE.get(user.getPresentPeriod()));
				user.setMaritalStatus(User.MARRIAGE_STATUS.get(user.getMaritalStatus()));
				user.setFristContactRelation(User.CONTACTS_FAMILY.get(user.getFristContactRelation()));
				user.setSecondContactRelation(User.CONTACTS_OTHER.get(user.getSecondContactRelation()));
				model.addAttribute("user", user);

				UserCardInfo info = userService.findUserBankCard(borrow.getUserId());
				model.addAttribute("bankCard", info);
				List<UserInfoImage> userInfoImage = this.userInfoImageService.selectImageByUserId(borrow.getUserId());
				model.addAttribute("InfoImage", userInfoImage);

				model.addAttribute("params", params);
				
				
				//查询征信信息
				RiskCreditUser riskCreditUser = riskUserService.findRiskCreditUserByAssetsId(String.valueOf(id));
				if(null!=riskCreditUser){
					model.addAttribute("riskCreditUser", riskCreditUser);
				}
				
				//规则查询 
				List<RiskRuleCal> riskRuleCalList = riskUserService.findRiskRuleCalByAssetsId(String.valueOf(id));
				model.addAttribute("riskRuleCalList", riskRuleCalList);
				
				
				url = "borrow/borrow_check";
				if (params.containsKey("bType")) {
					if (params.get("bType").equals("fangk")) {// 放款界面看到的状态
						url = "borrow/borrow_fangk_check";
					} else if (params.get("bType").toString().contains("fengk")) {// 风控界面看到的状态

						if (params.get("bType").equals("fengk_Trial")) {// 初审
							url = "borrow/borrow_trial_check";
						} else if (params.get("bType").equals("fengk_Review")) {// 复审
							url = "borrow/borrow_review_check";
						}
						// url = "borrow/fk_borrowList";
					}
					model.addAttribute("bType", params.get("bType"));
				}

			} else {
				// // 更新或者添加操作
				if (borrowOrder.getId() != null) {
					String key = BorrowOrder.REVIEW_BORROW + borrowOrder.getId();
					String value = key;

					if (jedisCluster.get(key) != null) {
						SpringUtils.renderDwzResult(response, false, "操作失败,原因：该订单正在被审核，请稍后操作！", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
					} else {

						jedisCluster.setex(BorrowOrder.REVIEW_BORROW + borrowOrder.getId(), BorrowOrder.REVIEW_BORROW_SECOND, value);
						// Thread.sleep(10000);
						Date nowDate = new Date();
						BorrowOrder borrowOrderR = borrowOrderService.findOneBorrow(borrowOrder.getId());
						if (BorrowOrder.borrowStatusMap_shenheFail.containsKey(borrowOrderR.getStatus()) && borrowOrderR.getStatus() != BorrowOrder.STATUS_CSBH) {// 审核失败的不让再继续审核了,除了初审驳回
							SpringUtils.renderDwzResult(response, false, "当前状态为:<b>" + borrowOrderR.getStatusName() + "</b>,该借款状态不支持继续审核！", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
						} else {

							BackUser backUser = loginAdminUser(request);
							borrowOrder.setUpdatedAt(nowDate);
							if (params.get("bType").equals("fengk_Trial")) {// 初审
								borrowOrder.setVerifyTrialTime(nowDate);
								borrowOrder.setVerifyTrialRemark(borrowOrder.getRemark());
								borrowOrder.setVerifyTrialUser(backUser.getUserAccount());
							} else if (params.get("bType").equals("fengk_Review")) {// 复审
								borrowOrder.setVerifyReviewTime(nowDate);
								borrowOrder.setVerifyReviewRemark(borrowOrder.getRemark());
								borrowOrder.setVerifyReviewUser(backUser.getUserAccount());
							} else if (params.get("bType").equals("fangk")) {// 放款审核

								borrowOrder.setVerifyLoanTime(new Date());
								borrowOrder.setVerifyLoanRemark(borrowOrder.getRemark());
								borrowOrder.setVerifyLoanUser(backUser.getUserAccount());

							}
 

							//重新放款
							if (borrowOrder.getStatus().intValue() ==Integer.parseInt( BorrowOrder.STATUS_FKZ+"2")) {
								
								if(borrowOrderR.getStatus().intValue()!=BorrowOrder.STATUS_HKZ&&!borrowOrderR.getPaystatus().equals(BorrowOrder.SUB_PAY_CSZT)){
									borrowOrder.setYurref(GenerateNo.payRecordNo("A"));
									borrowOrder.setPaystatus(BorrowOrder.SUB_PAY_CSZT);
									borrowOrder.setStatus(BorrowOrder.STATUS_FKZ);
									borrowOrder.setVerifyLoanRemark("重新放款："+borrowOrder.getRemark());
								}else{
									SpringUtils.renderDwzResult(response, false, "操作失败,原因：该订单不能被进行重新放款操作，如有疑问请联系技术人员！", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
									model.addAttribute("params", params);
									return url;
								}
							}
							borrowOrderService.updateById(borrowOrder);

							if (borrowOrderR.getStatus() == BorrowOrder.STATUS_DCS) {
								RiskCreditUser riskCreditUser = new RiskCreditUser();
								riskCreditUser.setAssetId(borrowOrderR.getId());
								riskCreditUser.setRiskStatus(6);
								borrowOrderService.updateRiskCreditUserById(riskCreditUser);
							} else if (borrowOrderR.getStatus() == BorrowOrder.STATUS_CSBH) {// 初审驳回后被救回
								RiskCreditUser riskCreditUser = new RiskCreditUser();
								riskCreditUser.setAssetId(borrowOrderR.getId());
								riskCreditUser.setRiskStatus(7);
								borrowOrderService.updateRiskCreditUserById(riskCreditUser);

								// 初审驳回后被救回需要冻结借款金额
								User user = userService.searchByUserid(borrowOrderR.getUserId());
								User newUser = new User();
								newUser.setId(user.getId());
								newUser.setAmountAvailable(String.valueOf(Integer.valueOf(user.getAmountAvailable()) - borrowOrderR.getMoneyAmount()));

								// if(Integer.parseInt(newUser.getAmountAvailable())>Integer.parseInt(user.getAmountMax())){
								// logger.error("退回额度出错！可用额度大于最大额度。将可用额度重置为最大额度！");
								// newUser.setAmountAvailable(user.getAmountAvailable());
								// }
								newUser.setUpdateTime(nowDate);
//								userService.updateByPrimaryKeyUser(newUser);
								logger.info("kou UserLimit sucess 初审驳回后被救回扣除用户可用额度！");

							}
							// 审核失败，退回可用额度
							if (BorrowOrder.borrowStatusMap_shenheFail.containsKey(borrowOrder.getStatus())) {
								User user = userService.searchByUserid(borrowOrderR.getUserId());
								User newUser = new User();
								newUser.setId(user.getId());
								newUser.setAmountAvailable(String.valueOf(Integer.valueOf(user.getAmountAvailable()) + borrowOrderR.getMoneyAmount()));
								newUser.setUpdateTime(nowDate);
								userService.updateByPrimaryKeyUser(newUser);
								logger.info("return UserLimit sucess 审核不通过恢复用户可用额度！");
							}

							// 放款审核通过，需要完善判断，防止前端修改状态
							if (borrowOrder.getStatus().intValue() == BorrowOrder.STATUS_FKZ) {
//								logger.info("调用第三方放款接口");
//								if (borrowOrderR != null && !borrowOrderR.getPaystatus().equals(BorrowOrder.SUB_PAY_SUCC)) {
//									final BorrowOrder borrowOrderT=borrowOrderR;
//									ThreadPool.getInstance().run(new Runnable() {
//										@Override
//										public void run() {
//											borrowOrderService.requestPay(borrowOrderT);
// 
//										}
//									});
//								
//									
//								}
								// 调用第三方去放款
							 
								
							}
							jedisCluster.del(key);
							// risk_credit_user

							SpringUtils.renderDwzResult(response, true, "操作成功", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());

						}
					}

				} else {
					// 增加
				}

			}

		} catch (Exception e) {
			if (url == null) {

				SpringUtils.renderDwzResult(response, false, "操作失败,原因：" + erroMsg, DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
			}
			logger.error("添加权限信息失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;

	}

	/**
	 * 跳过机审，初审通过
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @param borrowOrder
	 * @return
	 */
	@RequestMapping("saveUpdateBorrowTGJS")
	public String saveUpdateBorrowTGJS(HttpServletRequest request, HttpServletResponse response, Model model, BorrowOrder borrowOrder) {

		HashMap<String, Object> params = this.getParametersO(request);
		String url = null;
		String erroMsg = null;
		try {

			// // 更新或者添加操作
			if (borrowOrder.getId() != null) {
				String key = BorrowOrder.REVIEW_BORROW + borrowOrder.getId();
				String value = key;

				if (jedisCluster.get(key) != null) {
					SpringUtils.renderDwzResult(response, false, "操作失败,原因：该订单正在被审核，请稍后操作！", DwzResult.CALLBACK_CLOSECURRENT, params.get("parentId").toString());
				} else {

					jedisCluster.setex(BorrowOrder.REVIEW_BORROW + borrowOrder.getId(), BorrowOrder.REVIEW_BORROW_SECOND, value);
					BorrowOrder borrowOrderR = borrowOrderService.findOneBorrow(borrowOrder.getId());
					// 待机审核、机审失败的才可以
					if (borrowOrderR.getStatus().intValue() == BorrowOrder.STATUS_DCS
					//
					// || borrowOrderR.getStatus().intValue() ==
					// BorrowOrder.STATUS_JSJJ
					) {
						BackUser backUser = loginAdminUser(request);

						borrowOrder.setUpdatedAt(new Date());

						borrowOrder.setStatus(BorrowOrder.STATUS_CSTG);
						borrowOrder.setRemark("人工操作跳过机审！");

						borrowOrder.setVerifyTrialTime(new Date());
						borrowOrder.setVerifyTrialRemark(borrowOrder.getRemark());
						borrowOrder.setVerifyTrialUser(backUser.getUserName());

						borrowOrderService.updateById(borrowOrder);

						if (borrowOrderR.getStatus() == BorrowOrder.STATUS_DCS) {
							RiskCreditUser riskCreditUser = new RiskCreditUser();
							riskCreditUser.setAssetId(borrowOrderR.getId());
							riskCreditUser.setRiskStatus(6);
							borrowOrderService.updateRiskCreditUserById(riskCreditUser);
						}

						SpringUtils.renderDwzResult(response, true, "操作成功", DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId").toString());

					} else {

						SpringUtils.renderDwzResult(response, false, "操作失败,原因：该状态不能跳过机审或者已经过了机审！", DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId").toString());

					}
				}
			}

		} catch (Exception e) {
			if (url == null) {

				SpringUtils.renderDwzResult(response, false, "操作失败,原因：" + erroMsg, DwzResult.CALLBACK_CLOSECURRENTDIALOG, params.get("parentId").toString());
			}
			logger.error("跳过机审失败，异常信息:", e);
		}
		model.addAttribute(MESSAGE, erroMsg);
		model.addAttribute("params", params);
		return url;

	}

	/**
	 * 放款回调
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @param borrowOrder
	 * @return
	 */
	@RequestMapping("creditReCallBack")
	public void creditReCallBack(HttpServletRequest request, HttpServletResponse response, Model model) {

		// HashMap<String, Object> params = this.getParametersO(request);

		String borrowId = request.getParameter("bId");// 借款id，或者是其它唯一标识

		String isSuccess = request.getParameter("code");// 0000成功，其它失败。例如
		try {
			BorrowOrder borrowOrderR = borrowOrderService.findOneBorrow(Integer.parseInt(borrowId));
			// // 更新或者添加操作
			if (borrowOrderR != null) {

				if (borrowOrderR.getStatus().intValue() != BorrowOrder.STATUS_HKZ.intValue()) {// 放款成功
					Date fkDate = new Date();

					if (isSuccess.equals("0000")) {
						borrowOrderR.setLoanTime(fkDate);
						borrowOrderR.setStatus(BorrowOrder.STATUS_HKZ);
						Repayment repayment = new Repayment();
						repayment.setUserId(borrowOrderR.getUserId());
						repayment.setAssetOrderId(borrowOrderR.getId());
						repayment.setRepaymentAmount(Long.valueOf(borrowOrderR.getMoneyAmount()));
						repayment.setRepaymentedAmount(0L);
						repayment.setRepaymentPrincipal(Long.valueOf(borrowOrderR.getIntoMoney()));
						repayment.setRepaymentInterest(Long.valueOf(borrowOrderR.getLoanInterests()));
						repayment.setLateFeeApr(borrowOrderR.getLateFeeApr());
						repayment.setRepaymentTime(DateUtil.addDay(fkDate, borrowOrderR.getLoanTerm()));// 放款时间加上借款期限
						repayment.setCreatedAt(fkDate);
						repayment.setUpdatedAt(fkDate);
						repayment.setStatus(borrowOrderR.getStatus());
						repaymentService.insert(repayment);
						User user = userService.searchByUserid(borrowOrderR.getUserId());
						SendSmsUtil.sendSmsDiyCL(user.getUserPhone(), "你收到贷速侠打款" + borrowOrderR.getIntoMoney() / 100 + "元,预计很快到账，请注意查收！");

					} else {
						borrowOrderR.setUpdatedAt(fkDate);
						borrowOrderR.setStatus(BorrowOrder.STATUS_FKSB);
					}

				}
				borrowOrderService.updateById(borrowOrderR);
				SpringUtils.renderText(response, "true");
			} else {

				logger.error("放款回调，没有找到对应的借款信息：");
			}

		} catch (Exception e) {
			logger.error("放款回调失败，异常信息:", e);

		}

	}

	@RequestMapping("getUserLimitPage")
	public String getUserLimitPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		String url = "userInfo/userLimitRecordList";
		try {

			HashMap<String, Object> params = getParametersO(request);

			PageConfig<UserLimitRecord> pageConfig = borrowOrderService.finduserLimitPage(params);
			model.addAttribute("pm", pageConfig);

			model.addAttribute("params", params);// 用于搜索框保留值

		} catch (Exception e) {
			logger.error("getUserLimitPage error", e);
		}
		return url;
	}
	
	/**
	 * 导出对账Excel
	 */
	@RequestMapping("toDzExcel/{borrowStatus}")
	public void toDzExcel(HttpServletRequest request,HttpServletResponse response,@PathVariable("borrowStatus") String borrowStatus) {
		HashMap<String, Object> params = this.getParametersO(request);
		try {
			params.put(Constant.PAGE_SIZE, 50000);
			params.put("borrowStatus", borrowStatus);
			int totalPageNum=borrowOrderService.findParamsCount(params);
			OutputStream os = response.getOutputStream();
			response.reset();// 清空输出流
			ExcelUtil.setFileDownloadHeader(request, response, "订单对账统计.xls");
			response.setContentType("application/msexcel");// 定义输出类型
			SXSSFWorkbook workbook = new SXSSFWorkbook(10000);
			String[] titles = { "债权编号","第三方订单号","手机号码", "借款人","身份证号码","借款金额","实际到账金额","还款期限","放款时间","状态" };
			for (int i = 1; i <=totalPageNum; i++) {
				params.put(Constant.CURRENT_PAGE, i);
				PageConfig<BorrowOrder> pm = borrowOrderService.findPage(params);
				List<BorrowOrder> borrowList = pm.getItems();
				List<Object[]> contents = new ArrayList<Object[]>();
				for (BorrowOrder borrowOrder : borrowList) {
					Object[] conList = new Object[titles.length];
					conList[0] = borrowOrder.getId();
					conList[1] = borrowOrder.getOutTradeNo();
					conList[2] = borrowOrder.getUserPhone()==null?"":borrowOrder.getUserPhone();
					conList[3] = borrowOrder.getRealname()==null?"":borrowOrder.getRealname();
					conList[4] = borrowOrder.getIdNumber()==null?"":borrowOrder.getIdNumber();
					conList[5] = new BigDecimal(borrowOrder.getMoneyAmount()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
					conList[6] =new BigDecimal(borrowOrder.getIntoMoney()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
					conList[7] = borrowOrder.getLoanTerm()+"天";
					conList[8] = DateUtil.getDateFormat(borrowOrder.getLoanTime(),"yy-MM-dd hh:mm:ss");
					conList[9] = BorrowOrder.borrowStatusMap.get(borrowOrder.getStatus());
					contents.add(conList);
				}
				ExcelUtil.buildExcel(workbook, "用户列表", titles, contents, i, pm
						.getTotalPageNum(), os);
			}
		} catch (Exception e) {
			logger.error("导出excel失败", e);
		}

	}

	@RequestMapping("testxx")
	public void testxx(HttpServletRequest request, HttpServletResponse response, Model model) {

		try {
            //查询状态
// 			taskJob.queryPaysStateNotCmb();
//			taskJob.queryPaysStateCmb();
			HttpRequestCMBHL.getRequestNTQRYEBPStr();
//			System.out.println("zz");
//			taskJob.updateLoanTerm();

		} catch (Exception e) {
			logger.error("getUserLimitPage error", e);
		}

	}
}
